import xml.etree.ElementTree as ET
from os import getcwd
import os
import tqdm


classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair",
           "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]


def convert_annotation(list_file, xml_path):
    in_file = open(xml_path)
    tree=ET.parse(in_file)
    root = tree.getroot()

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult)==1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
        list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))


wd = getcwd()
if __name__ == "__main__":
    train_sets = [('2012', 'train'), ('2007', 'train')]
    test_sets = [('2007', 'test'), ('2012', 'test')]

    #for training
    for year, image_set in train_sets:
        # image_ids = open('D:/Data/VOC/Train/Vocdevkit2012/VOC%s/ImageSets/Main/%s.txt' % (year, image_set)).read().strip().split()
        image_ids = open('D:/Data/VOC/VOCdevkit/train/VOC%s/ImageSets/Main/trainval.txt' % (year)).read().strip().split()
        list_file = open('voc_%s_%s.txt' % (year, image_set), 'w')
        for image_id in tqdm.tqdm(image_ids):
            list_file.write('D:/Data/VOC/VOCdevkit/train/VOC%s/JPEGImages/%s.jpg' % (year, image_id))
            convert_annotation(list_file, xml_path='D:/Data/VOC/VOCdevkit/train/VOC%s/Annotations/%s.xml'%(year, image_id))
            list_file.write('\n')
        list_file.close()

    #for testing
    for year, image_set in test_sets:
        image_ids = open('D:/Data/VOC/VOCdevkit/test/VOC%s/ImageSets/Main/%s.txt' % (year, image_set)).read().strip().split()
        list_file = open('voc_%s_%s.txt' % (year, image_set), 'w')
        for image_id in tqdm.tqdm(image_ids):
            list_file.write('D:/Data/VOC/VOCdevkit/test/VOC%s/JPEGImages/%s.jpg' % (year, image_id))
            xml_path = 'D:/Data/VOC/VOCdevkit/test/VOC%s/Annotations/%s.xml'%(year, image_id)
            if os.path.exists(xml_path):
                convert_annotation(list_file, xml_path=xml_path)
            list_file.write('\n')
        list_file.close()

